//
//  Date+Extension.swift
//  JXHSinaWeiBo
//
//  Created by juxiaohui on 16/10/21.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import Foundation

extension Date {

    static func dateSting(createAt : String) -> String {
        
        let str = createAt
        
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale  = Locale.init(identifier: "en")
        // 将字符串时间转化给Date
        guard let createDate = fmt.date(from: str)  else {
            return ""
        }
        let nowDate = Date()
        let interval = Int(nowDate.timeIntervalSince(createDate))
        
        //小于1分钟
        if interval < 60 {
            return "刚刚"
        }
        
        //小于1小时
        if interval < 60 * 60 {
            return "\(interval / 60)分钟前"
        }
        
        // 小于一天
        if interval < 60 * 60 * 24 {
            return "\(interval / 60 / 60)小时前"
        }
        
        //昨天
        let calendar = NSCalendar.current //日历对象
        
        if calendar.isDateInYesterday(createDate) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeString = fmt.string(from: createDate)
            return timeString
        }
        
        let cmps = calendar.dateComponents([.year], from: createDate, to: nowDate)
        guard let year = cmps.year else {
            return ""
        }
        
        if year < 1 { //小于一年
            fmt.dateFormat = "MM-dd HH:mm"
            let timeString = fmt.string(from: createDate)
            return timeString
        }
        // 大于一年
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        let timeString = fmt.string(from: createDate)
        return timeString
    }
}
